(*
  Copyright (c) 2009 Barry Schwartz

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*)

open UTypes
  
type symbol = int

(* tables for mappings string -> int and int -> string *)

let symbol_table = Hashtbl.create 500
let name_table = ref (Array.make 500 [|  |])
let table_size = ref 1
  
(*
  We add the empty string as symbol since, for symbols obtained directly by |alloc_symbol|,
  |symbol_to_string| returns the empty string. Consequently, |string_to_symbol []| will not
  be equal to such a symbol. This ensures that these symbols cannot be faked.
*)
let _ = Hashtbl.add symbol_table [|  |] 0
  
let alloc_symbol () =
  let n = !table_size in
    table_size := n + 1;
    (* increase <name_table> if necessary *)
    if (Array.length !name_table) <= n then
      name_table :=
        Array.init (2 * (Array.length !name_table))
          (fun i ->
             if i < (Array.length !name_table)
             then !name_table.(i)
             else [|  |])
    else
      ();
    n
  
let add_symbol (str : uc_string) =
  let n = alloc_symbol () in
    (* add string to <symbol_table> and <name_table> *)
    Hashtbl.add symbol_table str n;
    !name_table.(n) <- str;
    n
      
let string_to_symbol str =
  try Hashtbl.find symbol_table str with | Not_found -> add_symbol str
    
let symbol_to_string sym = !name_table.(sym)
  
module SymbolMap =
  Map.Make
    (struct type t = int
            let compare : int -> int -> int = compare
     end)
    
(* Returns an associative list of the elements of <map>, in ascending
   order (a fact upon which parts of this program may rely). *)
let map_to_list map = SymbolMap.fold (fun k v l -> (k, v) :: l) map []

let rec list_to_map p =     (* Not a tail-recursive implementation. *)
  match p with
    | [] -> SymbolMap.empty
    | (k, v) :: remaining -> SymbolMap.add k v (list_to_map remaining)
